package com.pinyougou.sellergoods.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pinyougou.dao.BrandDao;
import com.pinyougou.entity.PageResult;
import com.pinyougou.pojo.Brand;
import com.pinyougou.sellergoods.service.BrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class BrandServiceImpl implements BrandService {
    @Autowired
    private BrandDao brandDao;

    @Override
    public Brand findById(Integer id) {
        Brand brand = brandDao.selectByPrimaryKey(id);
        return brand;
    }

    @Override
    public PageResult<Brand> findByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Brand> brandList = brandDao.selectAll();
        PageInfo<Brand> pageInfo = new PageInfo<>(brandList);
        PageResult<Brand> pageResult = new PageResult<>(pageInfo.getTotal(), pageInfo.getList());
        return pageResult;
    }

    @Override
    public List<Brand> findAll() {
        List<Brand> brandList = brandDao.selectAll();
        return brandList;
    }


    @Override
    public void save(Brand brand) {
        brandDao.insert(brand);
    }


    @Override
    public void update(Brand brand) {
        brandDao.updateByPrimaryKey(brand);
    }

    @Override
    public void delete(Integer[] ids) {
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", Arrays.asList(ids));
        brandDao.deleteByExample(example);
    }

    @Override
    public PageResult<Brand> findByPage(Brand brand, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Example example = null;
        if (brand != null) {
            example = new Example(Brand.class);
            Example.Criteria criteria = example.createCriteria();
            if (StringUtils.isNotBlank(brand.getName())) {
                criteria.andLike("name", "%" + brand.getName() + "%");
            }
        }
        List<Brand> brandList = brandDao.selectByExample(example);
        PageInfo<Brand> pageInfo = new PageInfo<>(brandList);
        PageResult<Brand> pageResult = new PageResult<>(pageInfo.getTotal(), pageInfo.getList());
        return pageResult;
    }

    @Override
    public List<Map> selectOptions() {
        List<Map> options=brandDao.selectOptions();
        return options;
    }
}
